package com.javen.controller;

import java.util.UUID;

import com.jfinal.core.Controller;
import com.jfinal.kit.HashKit;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.JsTicket;
import com.jfinal.weixin.sdk.api.JsTicketApi;
import com.jfinal.weixin.sdk.api.JsTicketApi.JsApiType;

/**
 * @author Javen
 * 2016年5月13日
 */
/**
 * 对整个Controller或者其中的方法添加JSSDK签名验证拦截器
 */

public class JSSDKController extends Controller{
	
	public void index(){
		String url = getPara("signurl");
		JsTicket jsApiTicket = JsTicketApi.getTicket(JsApiType.jsapi);
		String jsapi_ticket = jsApiTicket.getTicket();
		String nonce_str = create_nonce_str();
		
		String timestamp = create_timestamp();
		// 这里参数的顺序要按照 key 值 ASCII 码升序排序
		//注意这里参数名必须全部小写，且必须有序
		String  str = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str + "&timestamp=" + timestamp + "&url=" + url;

		String signature = HashKit.sha1(str);
		renderJson(new Record().set("appId", ApiConfigKit.getApiConfig().getAppId()).set("nonceStr", nonce_str)
				.set("timestamp", timestamp).set("signature", signature));
		
	}
	
	private static String create_timestamp() {
		return Long.toString(System.currentTimeMillis() / 1000);
	}

	private static String create_nonce_str() {
		return UUID.randomUUID().toString();
	}
}
